import importlib
import logging
import operator
import re
import traceback
import uuid
from datetime import datetime
from django.http import JsonResponse
# Create your views here.
from rest_framework.views import APIView
from utils.connect_redis import connect_redis
from utils.connect_mysql import connect_boss

# 双呼
class Makecall(APIView):
    def post(self, request):
        print('request.data',request.data)
        logger = logging.getLogger('log')
        try:
            try:
                telA = request.data['telA']
                telB = request.data['telB']
                recordFlag = request.data['recordFlag']
                account_id = request.data['account_id']
                account = request.data['account']
                identify = request.data['identify']
            except:
                return JsonResponse({'code': 500, 'msg': '缺少参数'})
            print(1111111111111111111111111111111111111)
            conn = connect_boss()
            if conn == 500:
                return JsonResponse({'code': 510, 'msg': '数据库连接失败'})
            cur = conn.cursor()
            ret1 = re.match(r"^1[3456789]\d{9}$", telB)
            if ret1:
                pass
            else:
                ret2 = re.match('\\d{2,3}\\d{6,8}', str(int(telB)))
                if ret2:
                    pass
                else:
                    return JsonResponse({'msg': '号码格式错误', 'code': 1001})
            print(2222222222222222222222222222222222222222)
            sql1 = """SELECT account_balance,is_overdraw FROM zb_account WHERE id={} AND status=0""".format(account_id)
            cur.execute(sql1)
            money_data = cur.fetchone()
            if money_data:
                money = money_data[0]
                is_overdraw = money_data[1]
            else:
                return JsonResponse({'msg': '企业未启用', 'code': 501})
            if float(money) <= 0:
                if is_overdraw:
                    return JsonResponse({'msg': '余额不足', 'code':1001})
                else:
                    pass
            print(3333333333333333333333333333333333333333333333333333333)
            sql2 = """SELECT COUNT(*) FROM black_{} WHERE bnumber='{}' AND pro_id=3""".format(identify,telB)
            sql3 = """SELECT COUNT(*) FROM anum_{} WHERE anumber='{}' AND pro_id=3""".format(identify,telA)
            cur.execute(sql2)
            count2 = cur.fetchone()[0]
            cur.execute(sql3)
            count3 = cur.fetchone()[0]
            if count3 >= 300:
                return JsonResponse({'msg': '主叫达到日呼限制次数', 'code':1001 })
            if count2 >= 300:
                return JsonResponse({'msg': '被叫达到日呼限制次数', 'code': 1001})
            sql = """SELECT pool_name FROM zb_NumX_pool WHERE account_id={} AND pro_id=3 AND status=0 AND is_conceal_xpool='0'""".format(
                account_id)
            print(11111111111111111111111000000,sql)
            cur.execute(sql)
            group = cur.fetchone()
            print(group)
            if group:
                groupxname = group[0]
            else:
                return JsonResponse({'msg': '选择号码池失败', 'code': 501})
            r = connect_redis(17)
            print(4444444444444444444444444444444444444444444)
            while True:
                Ckeys = [i for i in r.hkeys('Cpool_' + groupxname)]
                Nkeys = [i for i in r.hkeys('Xpool_' + groupxname)]
                Nvals = [int(i) for i in r.hvals('Xpool_' + groupxname)]
                if not Nkeys:
                    return JsonResponse({'code': 505, 'msg': '当前x池无可用x号码'})
                if len(Ckeys) >= len(Nkeys):
                    r.delete('Cpool_' + groupxname)
                    # r.hmset('Cpool_' + groupxname, {'a': 0})
                    # continue
                Xkeys = []
                Xvals = []
                for i in range(len(Nkeys)):
                    if Nkeys[i] not in Ckeys:
                        Xkeys.append(Nkeys[i])
                        Xvals.append(Nvals[i])
                Xdict = dict(zip(Xkeys, Xvals))
                Xpule = sorted(Xdict.items(), key=operator.itemgetter(1))
                if not Xpule:
                    pass
                try:
                    print('Xpule', Xpule)
                    Xnumber = Xpule[-1][0]
                    limitx = Xpule[-1][-1]

                except:
                    print(len([i for i in r.hkeys('Xpool_' + groupxname)]))
                    if len([i for i in r.hkeys('Xpool_' + groupxname)]) == 0:
                        return JsonResponse({'code': 505, 'msg': '当前x池无可用x号码'})
                    Xnumber = Xpule[-1][0]
                    limitx = Xpule[-1][-1]
                if int(limitx) <= 0:
                    Cvals = [i for i in r.hvals('Cpool_' + groupxname)]
                    if len(Cvals) == 0:
                        return JsonResponse({'code': 505, 'msg': '当前x池无可用并发'})
                    else:
                        r.delete('Cpool_' + groupxname)
                        r.hmset('Cpool_' + groupxname, {'a': 0})
                        continue
                r.hset('Cpool_' + groupxname, Xnumber, 0)
                sqlx = """SELECT COUNT(*) FROM xnum_{} WHERE xnumber='{}';""".format(identify, Xnumber)
                cur.execute(sqlx)
                countx = cur.fetchall()[0][0]
                if countx < 2000:
                    telX = Xnumber
                    break
                else:
                    r.hdel('Xpool_' + groupxname, Xnumber)
                    r.hdel('Cpool_' + groupxname, Xnumber)
                    r.hset('Rpool_' + groupxname, Xnumber, 0)
                    continue
            sql = """SELECT a.appkey,a.bind_url,a.p_gateway_name,d.acc_name FROM (((zb_private_gateway a JOIN 
            zb_NumX_pool b ON a.id=b.private_gateway_id) JOIN zb_number_x c ON b.id=c.groupx_id)
             JOIN zb_private_acc d ON c.private_acc_id = d.id) WHERE c.xnumber='{}'
            """.format(telX)
            cur.execute(sql)
            private_data = cur.fetchone()
            try:
                name = private_data[2]
                private_acc = private_data[3]
                appkey = private_data[0]
                bind_url = private_data[1]
            except:
                return JsonResponse({'code': 511, 'msg': '获取中间号信息出错'})
            # packpath = "utils." + name.split('-')[0]
            # utils.四川移动
            packpath = "utils.1221"
            params = importlib.import_module(packpath)
            userData = ''
            userData += account + ','
            userData += private_acc + ','
            userData += name + ','
            userData += groupxname + ','
            userData += telA + ','
            userData += telB + ','
            userData += telX
            my_uuid = str(re.sub('-', '', str(uuid.uuid1())))[0:16]
            print('uuid',my_uuid)
            r.set('{}'.format(my_uuid), userData)
            print('userData',userData)
            result = params.PhoneBindInter(telA, telX, telB, appkey, bind_url, recordFlag=recordFlag,userData=my_uuid)

            if result:
                res = result[0]
                xnum = result[1]
            else:
                return JsonResponse({'code': 10011, 'msg': '请求超时'})
            create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(create_time)
            if res["resultcode"] == '0':
                count = int(r.hget('Xpool_' + groupxname, telX))
                r.hset('Xpool_' + groupxname, telX, count - 1)
                try:
                    sql = """INSERT INTO xnum_{} values (0,3,'{}','{}');""".format(identify, telX, create_time)
                    cur.execute(sql)
                    conn.commit()
                except Exception as e:
                    print(e)
                    conn.rollback()
                try:
                    sql = """INSERT INTO black_{} values (0,3,'{}','{}');""".format(identify, telB, create_time)
                    cur.execute(sql)
                    conn.commit()
                except Exception as e:
                    print(e)
                    conn.rollback()
                try:
                    sql = """INSERT INTO anum_{} values (0,3,'{}','{}');""".format(identify, telA, create_time)
                    cur.execute(sql)
                    conn.commit()
                except Exception as e:
                    print(e)
                    conn.rollback()
                res['xnum'] = xnum
                cur.close()
                conn.close()
                return JsonResponse({'code': 200, 'data': res})
            elif res['resultcode'] == '100001':
                return JsonResponse({'code': 1001, 'msg': '请求体参数不全或参数格式错误'})
            elif res['resultcode'] == '100002':
                return JsonResponse({'code': 1003, 'msg': '响应超时'})
            elif res['resultcode'] == '100003':
                logger.error('{}---{}---{}'.format(params, res['resultcode'], identify))
                return JsonResponse({'code': 1008, 'msg': '平台并发上限'})
            elif res['resultcode'] == '100004':
                logger.error('{}---{}---{}'.format(params, res['resultcode'], identify))
                return JsonResponse({'code': 1009, 'msg': '运营商系统错误'})
            elif res['resultcode'] == '100005':
                logger.error('{}---{}---{}'.format(params, res['resultcode'], identify))
                return JsonResponse({'code': 10011, 'msg': '风控受限'})
            elif res['resultcode'] == '100006':
                logger.error('{}---{}---{}'.format(params, res['resultcode'], identify))
                return JsonResponse({'code': 10012, 'msg': '平台余额不足,请联系管理员'})
            elif res['resultcode'] == '100007':
                logger.error('{}---{}---{}'.format(params, res['resultcode'], identify))
                return JsonResponse({'code': 10013, 'msg': '主叫号码未在运营商报备'})
            else:
                logger.error('{}---{}---{}'.format(params, res['resultcode'], identify))
                return JsonResponse({'code': 10010, 'msg': '其他错误请联系管理员'})
        except Exception as e:
            logger.error('测试bug{}'.format(str(e)))
            logger.error('测试bug{}'.format(traceback.format_exc()))
            return JsonResponse({'code': 501, 'msg': '呼叫错误'})